package com.itheima.service.Impl;

import com.itheim.client.pojo.User;
import com.itheim.client.vo.UserVo;
import com.itheima.client.mapper.LoginMapper;
import com.itheima.common.R;
import com.itheima.common.TokenHolder;
import com.itheima.service.LoginService;
import com.itheima.util.JwtUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author longbosheng
 * @Date 2022/6/19 16:17
 * @PackageName:com.itheima.service.serviceImpl
 * @ClassName: LoginServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Log4j2
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public R login(User user) {
        //判断手机号和验证码是否有问题
        String c = redisTemplate.opsForValue().get(user.getPhone());
        String code = user.getCode();

        c = c.replaceAll("\\p{C}", "");//替换字符串中不可见字符
        code = code.replaceAll("\\p{C}", "");//替换字符串中不可见字符

        if (!code.equals(c)){
            return R.error("验证码错误！");
        }
        //判断在数据库是否有该账户
        UserVo resultUser = loginMapper.selectUser(user);
        if (resultUser!=null){

            String token2 = JwtUtil.getToken2(resultUser.getId(), resultUser.getPhone());
            resultUser.setToken(token2);
            redisTemplate.opsForValue().set(token2, resultUser.getId());
            /*设置用户id在TokenHolder*/
            TokenHolder.setCurrentId(resultUser.getId());
            log.info("有账号，自动登录");
            resultUser.setUserName("阿伯");
            return R.success(resultUser);
        }else {
            int regist = loginMapper.insert(user);
            log.info("无账号，自动注册");
            if (regist>0){
                UserVo newuser = loginMapper.selectUser(user);
                String token2 = JwtUtil.getToken2(newuser.getId(), newuser.getPhone());
                newuser.setToken(token2);
                redisTemplate.opsForValue().set(token2, newuser.getId());
                /*设置用户id在TokenHolder*/
                TokenHolder.setCurrentId(newuser.getId());
                return R.success(newuser);
            }
        }
        return R.error("登录功能异常");
    }
}
